<template>
  <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" title="MIS+" :visible.sync="dialogPvVisible" width="80%">
    <div style="background: #ffffff">
<!--      <div class="filter-container">-->
<!--        <el-form ref="dataForm" :model="listQuery"   label-width="80px" class="searchform" inline>-->

<!--          <el-form-item :label="$t('bs.spareparts')" prop="spareparts">-->
<!--            <el-input-->
<!--              v-model="listQuery.spareparts"-->
<!--              class="filter-item"-->
<!--              :placeholder="$t('bs.spareparts')"-->
<!--              style="width: 204px;"-->
<!--              @keyup.enter.native="handleFilter"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item :label="$t('bs.process')" prop="process">-->
<!--            <el-input-->
<!--              v-model="listQuery.process"-->
<!--              class="filter-item"-->
<!--              :placeholder="$t('bs.process')"-->
<!--              style="width: 204px;"-->
<!--              @keyup.enter.native="handleFilter"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item :label="$t('bs.specification\n')" prop="specification">-->
<!--            <el-input-->
<!--              v-model="listQuery.specification"-->
<!--              class="filter-item"-->
<!--              :placeholder="$t('bs.specification\n')"-->
<!--              style="width: 204px;"-->
<!--              @keyup.enter.native="handleFilter"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item :label="$t('bs.supplier')" prop="supplier">-->
<!--            <el-input-->
<!--              v-model="listQuery.supplier"-->
<!--              class="filter-item"-->
<!--              :placeholder="$t('bs.supplier')"-->
<!--              style="width: 204px;"-->
<!--              @keyup.enter.native="handleFilter"-->
<!--            />-->
<!--          </el-form-item> <el-form-item :label="$t('bs.spm')" prop="url">-->
<!--          <el-input-->
<!--            v-model="listQuery.spm"-->
<!--            class="filter-item"-->
<!--            :placeholder="$t('bs.spm')"-->
<!--            style="width: 204px;"-->
<!--            @keyup.enter.native="handleFilter"-->
<!--          />-->
<!--        </el-form-item>-->
<!--          <el-form-item :label="$t('bs.sap_code')" prop="sap_code">-->
<!--            <el-input-->
<!--              v-model="listQuery.sap_code"-->
<!--              class="filter-item"-->
<!--              :placeholder="$t('bs.sap_code')"-->
<!--              style="width: 204px;"-->
<!--              @keyup.enter.native="handleFilter"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item :label="$t('bs.min_stock')" prop="min_stock">-->
<!--            <el-input-->
<!--              v-model="listQuery.min_stock"-->
<!--              class="filter-item"-->
<!--              :placeholder="$t('bs.min_stock')"-->
<!--              style="width: 204px;"-->
<!--              @keyup.enter.native="handleFilter"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          &lt;!&ndash;          <el-form-item :label="$t('bs.station')" prop="station">&ndash;&gt;-->
<!--          &lt;!&ndash;            <el-select v-model="listQuery.st_id" filterable clearable placeholder="请选择工站" disabled>&ndash;&gt;-->
<!--          &lt;!&ndash;              <el-option&ndash;&gt;-->
<!--          &lt;!&ndash;                v-for="item in station_list"&ndash;&gt;-->
<!--          &lt;!&ndash;                :key="item.id"&ndash;&gt;-->
<!--          &lt;!&ndash;                :label="item.station_name"&ndash;&gt;-->
<!--          &lt;!&ndash;                :value="item.id">&ndash;&gt;-->
<!--          &lt;!&ndash;              </el-option>&ndash;&gt;-->
<!--          &lt;!&ndash;            </el-select>&ndash;&gt;-->


<!--          &lt;!&ndash;          </el-form-item>&ndash;&gt;-->

<!--          <el-form-item>-->
<!--            <el-button v-waves class="filter-item" @click="handleFilter">-->
<!--              {{ $t('table.search') }}-->
<!--            </el-button>-->
<!--            <el-button class="filter-item" style="margin-left: 10px;" @click="handleFilterReset">-->
<!--              {{$t('bs.reset')}}-->
<!--            </el-button>-->
<!--          </el-form-item>-->
<!--        </el-form>-->

<!--      </div>-->
      <div style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;">
        <el-table
          key="id"
          v-loading="listLoading"
          :data="list"
          fit
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="fileds.lineName.is_show==1" :label="fileds.lineName.title">
            <template slot-scope="{row}">
              {{ row.lineName }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.machineDesEn.is_show==1" :label="fileds.machineDesEn.title">
            <template slot-scope="{row}">
              {{ row.machineDesEn }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.maintOrder.is_show==1" :label="fileds.maintOrder.title">
            <template slot-scope="{row}">
              {{ row.maintOrder }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.pmType.is_show==1" :label="fileds.pmType.title">
            <template slot-scope="{row}">
              {{ row.pmType }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.isBkd.is_show==1" :label="fileds.isBkd.title">
            <template slot-scope="{row}">
              {{ row.isBkd }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.inventoryNo.is_show==1" :label="fileds.inventoryNo.title">
          <template slot-scope="{row}">
            {{ row.inventoryNo }}
          </template>
        </el-table-column>

          <el-table-column v-if="fileds.areaName.is_show==1" :label="fileds.areaName.title">
            <template slot-scope="{row}">
              {{ row.areaName }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.status.is_show==1" :label="fileds.status.title">
            <template slot-scope="{row}">
              {{ row.status }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.abcIndicator.is_show==1" :label="fileds.abcIndicator.title">
            <template slot-scope="{row}">
              {{ row.abcIndicator }}
            </template>
          </el-table-column>

          <el-table-column v-if="fileds.errorNameEn.is_show==1" :label="fileds.errorNameEn.title">
            <template slot-scope="{row}">
              {{ row.errorNameEn }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.errorld.is_show==1" :label="fileds.errorld.title">
            <template slot-scope="{row}">
              {{ row.errorld }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.subErrorinfo.is_show==1" :label="fileds.subErrorinfo.title">
            <template slot-scope="{row}">
              {{ row.subErrorinfo }}
            </template>
          </el-table-column>



<!--          <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">-->
<!--            <template slot-scope="{row,$index}">-->
<!--              <el-button circle icon="el-icon-edit" size="small" @click="handleUpdate(row)" />-->

<!--              <el-popconfirm-->
<!--                title="确定删除吗？"-->
<!--                @confirm="handleDelete([row.id])"-->
<!--              >-->
<!--                <el-button slot="reference" style="margin-left: 8px" circle icon="el-icon-delete" size="small" />-->
<!--              </el-popconfirm>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>

<!--        <pagination-->
<!--          v-show="total>0"-->
<!--          :limit.sync="listQuery.limit"-->
<!--          :page.sync="listQuery.page_no"-->
<!--          :total="total"-->
<!--          @pagination="getList"-->
<!--        />-->

      </div>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogPvVisible = false">
        {{ $t('table.cancel') }}
      </el-button>
      <!--      <el-button type="primary" @click="subbj">-->
      <!--        {{ $t('table.confirm') }}-->
      <!--      </el-button>-->
    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px">
        <el-row :gutter="2">

          <el-col :span="12">
            <el-form-item :label="$t('bs.spareparts')" prop="spareparts">
              <el-input v-model="temp.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.process')" prop="process">
              <el-input v-model="temp.process" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.specification')" prop="specification">
              <el-input v-model="temp.specification" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.spm')" prop="spm">
              <el-input v-model="temp.spm" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.sap_code')" prop="sap_code">
              <el-input v-model="temp.sap_code" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.min_stock')" prop="min_stock">
              <el-input v-model="temp.min_stock" type="number" />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item :label="$t('bs.station')" prop="station">-->
          <!--              <el-select v-model="temp.st_id" filterable placeholder="请选择工站">-->
          <!--                <el-option-->
          <!--                  v-for="item in station_list"-->
          <!--                  :key="item.id"-->
          <!--                  :label="item.station_name"-->
          <!--                  :value="item.id">-->
          <!--                </el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </el-dialog>
</template>

<script>
import {fetchList, createData, updateData, delData, fetchOne} from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect' // secondary package based on el-pagination

export default {
  name: 'misDetail',
  components: { CyTreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      station_list:[],
      multipleSelection:[],
      selectbj:false,
      total:0,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {

        }
      },
      queryMap:{},
      listLoading:false,
      list:[],
      fileds: {
        // areaName: { filed: 'areaName', title: 'Department', is_show: '1' },
        lineName: { filed: 'lineName', title: 'Line', is_show: '1' },
        machineDesEn: { filed: 'machineDesEn', title: 'Component name', is_show: '1' },
        maintOrder: { filed: 'maintOrder', title: 'Maintenance Order', is_show: '1' },
        pmType: { filed: 'pmType', title: 'PM TyPE', is_show: '1' },
        isBkd: { filed: 'isBkd', title: 'isBkd', is_show: '1' },
        inventoryNo: { filed: 'inventoryNo', title: 'inventoryNo', is_show: '1' },
        areaName: { filed: 'areaName', title: 'Area name', is_show: '1' },
        status: { filed: 'status', title: 'status', is_show: '1' },
        abcIndicator: { filed: 'abcIndicator', title: 'Device type', is_show: '1' },
        errorNameEn: { filed: 'errorNameEn', title: 'Operation details', is_show: '1' },
        errorld: { filed: 'areaName', title: 'Issue Category', is_show: '1' },
        subErrorinfo: { filed: 'areaName', title: 'Issue Subcategory', is_show: '1' },

      },
      checked: true,
      tablesetvisible: false,
      tableKey: 0,

      showReviewer: false,
      temp: {
        id: '', name: '', process: '', specification: '', supplier: '', spm: '', sap_code: '', min_stock: '', st_id: '' },


      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '关键备件名称不能为空', trigger: 'change' }],
      },
      downloadLoading: false

    }
  },
  mounted() {
    //  this.getList()
    // this.getStationList();
    // this.dialogPvVisible=true;
  },
  methods: {
    show(list){
      // this.listQuery.st_id=id;
      // this.temp.st_id=id;
      // console.log('查询条件',this.listQuery)
      // this.handleFilter();
      this.list=list;
      this.dialogPvVisible=true;
    },
    getStationList(){
      this.listLoading = true
      fetchList({  page_no: 1,
        limit: 100,
        sort: 'id',}, 'sl_view_station').then(response => {
        if (response.data && response.data.items) {
          this.station_list = response.data.items
        }
        this.listLoading = false
      })
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(this.multipleSelection.map(item=>item.id))
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'spare_parts').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        st_id:this.listQuery.st_id,
        where: {}
      }
      this.handleFilter()
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.dialogPvVisible=true;
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {  id: '', name: '', process: '', specification: '', supplier: '', spm: '', sap_code: '', min_stock: '', st_id: this.temp.st_id }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'spare_parts',
            add: this.temp
          }
          createData({ data: [data] }, 'spare_parts').then(() => {
            this.handleFilter()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'spare_parts',
            update: this.temp
          }
          updateData({ data: [data] }, 'spare_parts').then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.handleFilter()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(ids) {
      console.log("执行删除")
      delData({ id: ids.join(',') }, 'spare_parts').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list=[];
        this.total=0;
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 268px;
}
</style>

